using Identity.Application.Contracts.Common;
using Identity.Application.Permissions.Commands;
using Identity.Application.Permissions.Interfaces;
using MediatR;

namespace Identity.Application.Permissions.CommandHandlers;

public class DeletePermissionCommandHandler : IRequestHandler<DeletePermissionCommand, Result>
{
    private readonly IPermissionsRepository _permissionsRepository;
    private readonly IUnitOfWork _unitOfWork;
    public DeletePermissionCommandHandler(IPermissionsRepository permissionsRepository, IUnitOfWork unitOfWork)
    {
        _permissionsRepository = permissionsRepository;
        _unitOfWork = unitOfWork;
    }

    public async Task<Result> Handle(DeletePermissionCommand request, CancellationToken cancellationToken)
    {
        var permission = await _permissionsRepository.GetPermissionByIdAsync(request.Id);
        if (permission == null) return Result.Failure("该权限找不到");

        await _permissionsRepository.DeleteAsync(permission);
        await _unitOfWork.SaveChangesAsync(cancellationToken);
        return Result.Success();
    }
}